<?php
require_once(dirname(__FILE__) . "/../system/common.inc.php");
$dopost = isset($dopost) ? $dopost : '';
$buyid  = isset($out_trade_no) ? HtmlReplace($out_trade_no, 1) : '';
if ($dopost === 'alipay')
{
    if (!file_exists(DEDEDATA . '/payment/alipay.php'))
    {
        echo "fail";
    }
    require_once DEDEDATA . '/payment/alipay.php';
    $config = array(
        "sign_type"   => "RSA2",
        "appid"       => $payment['app_id'],
        "private_key" => $payment['merchant_private_key'],
        "public_key"  => $payment['alipay_public_key'],
    );
    //支付宝
    try
    {
        //实例支付对象
        $pay = \AliPay\Web::instance($config);
        unset($_REQUEST['dopost']);
        unset($_REQUEST['sign_type']);
        $data = $pay->notify(false, $_REQUEST);
        if (isset($data['trade_no']) && !empty($data['trade_no']))
        {
            $result = $pay->query($data['out_trade_no']);
            if ($result['trade_status'] === "TRADE_SUCCESS")
            {
                $buyid = $data['out_trade_no'];
                if (substr($buyid, 0, 3) == 'KE-')
                {
                    $arr = $dsql->GetOne("SELECT * FROM #@__shops_orders WHERE oid = '{$buyid}'");
                    if (is_array($arr))
                    {
                        $mid          = $arr['userid'];
                        $arr['money'] = $arr['priceCount'];
                        $memarr       = $dsql->GetOne("SELECT uname FROM #@__member WHERE mid = '" . $mid . "'");
                        $username     = $memarr['uname'];
                        if ($arr['state'] > 0)
                        {
                            if ($cfg_sendmail_bysmtp == 'Y' && !empty($cfg_smtp_server) && !empty($cfg_adminemail))
                            {
                                $mailtitle = "【{$cfg_webname}】新订单通知";
                                $mailbody  = '';
                                $mailbody  .= "用户昵称：" . $username . "\r\n";
                                $mailbody  .= "订单编号：" . $data['out_trade_no'] . "\r\n";
                                $mailbody  .= "商品名称：" . $data['subject'] . "\r\n";
                                $mailbody  .= "支付方式：支付宝支付\r\n";
                                $mailbody  .= "交易金额：" . $data['total_amount'] . "\r\n";
                                $mailbody  .= "支付时间：" . date('Y-m-d H:i:s', time()) . "\r\n";
                                $mailtype  = 'TXT';
                                require_once(DEDEINC . '/libraries/mail.class.php');
                                $smtp        = new smtp($cfg_smtp_server, $cfg_smtp_port, true, $cfg_smtp_usermail, $cfg_smtp_password);
                                $smtp->debug = 0;
                                $smtp->sendmail($cfg_adminemail, $cfg_webname, $cfg_smtp_usermail, $mailtitle, $mailbody, $mailtype);
                            }
                            echo "success";
                            exit;
                        }
                        /* 改变订单状态_支付成功 */
                        $sql = "UPDATE `#@__shops_orders` SET `state`='1', paytype='11' WHERE `oid`='$buyid' AND `userid`='" . $mid . "'";
                        if ($dsql->ExecuteNoneQuery($sql))
                        {
                            //作者：覃小华 2019年10月18日14:08:11 推广购课部分
                            //1、推荐人加佣金 2、付款人改成已购买用户  3、写收益记录
                            $typearr = $dsql->GetOne("SELECT typename FROM  #@__arctype WHERE id = '" . $arr['pid'] . "' ");
                            $tjrarr  = $dsql->GetOne("SELECT tjrmid FROM #@__member WHERE mid = '" . $mid . "'");
                            if (!empty($tjrarr['tjrmid']))
                            {
                                global $cfg_keyjbl;
                                $time    = time();
                                $yongjin = $arr['money'] * $cfg_keyjbl / 100;
                                $yongjin = number_format($yongjin, 2);
                                $tjrmid  = $tjrarr['tjrmid'];
                                $sql     = "UPDATE #@__member set shouyi = (shouyi + $yongjin) WHERE mid = '$tjrmid'";
                                $dsql->ExecuteNoneQuery($sql);
                                $sql = "UPDATE #@__member SET yigoumai = '1' WHERE mid = '" . $mid . "'";
                                $dsql->ExecuteNoneQuery($sql);
                                $sql = "INSERT INTO #@__jj_shouyi (`tjrmid`,`mid`,`jine`,`chanpin`,`yongjin`,`time`,`tid`  ) VALUES ('$tjrmid','" . $mid . "','" . $arr['money'] . "','" . $typearr['typename'] . "','$yongjin','$time','" . $arr['pid'] . "')";
                                $dsql->ExecuteNoneQuery($sql);
                            }
                            //推荐end
                            if ($cfg_sendmail_bysmtp == 'Y' && !empty($cfg_smtp_server) && !empty($cfg_adminemail))
                            {
                                $mailtitle = "【{$cfg_webname}】新订单通知";
                                $mailbody  = '';
                                $mailbody  .= "用户昵称：" . $username . "\r\n";
                                $mailbody  .= "订单编号：" . $data['out_trade_no'] . "\r\n";
                                $mailbody  .= "商品名称：" . $data['subject'] . "\r\n";
                                $mailbody  .= "支付方式：支付宝支付\r\n";
                                $mailbody  .= "交易金额：" . $data['total_amount'] . "\r\n";
                                $mailbody  .= "支付时间：" . date('Y-m-d H:i:s', time()) . "\r\n";
                                $mailtype  = 'TXT';
                                require_once(DEDEINC . '/libraries/mail.class.php');
                                $smtp        = new smtp($cfg_smtp_server, $cfg_smtp_port, true, $cfg_smtp_usermail, $cfg_smtp_password);
                                $smtp->debug = 0;
                                $smtp->sendmail($cfg_adminemail, $cfg_webname, $cfg_smtp_usermail, $mailtitle, $mailbody, $mailtype);
                            }
                            echo "success";
                            exit;
                        }
                    }
                }
                else if (preg_match("/M[0-9]+T[0-9]+RN[0-9]/", $buyid))
                {
                    $arr = $dsql->GetOne("SELECT * FROM #@__member_operation WHERE buyid = '{$buyid}'");
                    if (is_array($arr))
                    {
                        $product  = $arr['product'];
                        $pname    = $arr['pname'];
                        $pid      = $arr['pid'];
                        $mid      = $arr['mid'];
                        $memarr   = $dsql->GetOne("SELECT uname FROM #@__member WHERE mid = '" . $mid . "'");
                        $username = $memarr['uname'];
                        if ($arr['sta'] == 2)
                        {
                            if ($cfg_sendmail_bysmtp == 'Y' && !empty($cfg_smtp_server) && !empty($cfg_adminemail))
                            {
                                $mailtitle = "【{$cfg_webname}】新订单通知";
                                $mailbody  = '';
                                $mailbody  .= "用户昵称：" . $username . "\r\n";
                                $mailbody  .= "订单编号：" . $data['out_trade_no'] . "\r\n";
                                $mailbody  .= "商品名称：" . $data['subject'] . "\r\n";
                                $mailbody  .= "支付方式：支付宝支付\r\n";
                                $mailbody  .= "交易金额：" . $data['total_amount'] . "\r\n";
                                $mailbody  .= "支付时间：" . date('Y-m-d H:i:s', time()) . "\r\n";
                                $mailtype  = 'TXT';
                                require_once(DEDEINC . '/libraries/mail.class.php');
                                $smtp        = new smtp($cfg_smtp_server, $cfg_smtp_port, true, $cfg_smtp_usermail, $cfg_smtp_password);
                                $smtp->debug = 0;
                                $smtp->sendmail($cfg_adminemail, $cfg_webname, $cfg_smtp_usermail, $mailtitle, $mailbody, $mailtype);
                            }
                            echo "success";
                            exit;
                        }
                        //更新交易状态为已付款
                        $sql = "UPDATE `#@__member_operation` SET `sta`='1' WHERE `buyid`='$buyid' AND `mid`='" . $mid . "'";
                        $dsql->ExecuteNoneQuery($sql);

                        /* 改变点卡订单状态_支付成功 */
                        if ($product == "card")
                        {
                            $row = $dsql->GetOne("SELECT cardid FROM #@__moneycard_record WHERE ctid='$pid' AND isexp='0' ");;
                            //如果找不到某种类型的卡，直接为用户增加金币
                            if (!is_array($row))
                            {
                                $nrow   = $dsql->GetOne("SELECT num FROM #@__moneycard_type WHERE pname = '{$pname}'");
                                $dnum   = $nrow['num'];
                                $sql1   = "UPDATE `#@__member` SET `money`=money+'{$nrow['num']}' WHERE `mid`='" . $mid . "'";
                                $oldinf = "已经充值了" . $nrow['num'] . "金币到您的帐号！";
                            }
                            else
                            {
                                $cardid = $row['cardid'];
                                $sql1   = " UPDATE #@__moneycard_record SET uid='" . $mid . "',isexp='1',utime='" . time() . "' WHERE cardid='$cardid' ";
                                $oldinf = '您的充值密码是：<font color="green">' . $cardid . '</font>';
                            }
                            //更新交易状态为已关闭
                            $sql2 = " UPDATE #@__member_operation SET sta=2,oldinfo='$oldinf' WHERE buyid='$buyid'";
                            if ($dsql->ExecuteNoneQuery($sql1) && $dsql->ExecuteNoneQuery($sql2))
                            {
                                if ($cfg_sendmail_bysmtp == 'Y' && !empty($cfg_smtp_server) && !empty($cfg_adminemail))
                                {
                                    $mailtitle = "【{$cfg_webname}】新订单通知";
                                    $mailbody  = '';
                                    $mailbody  .= "用户昵称：" . $username . "\r\n";
                                    $mailbody  .= "订单编号：" . $data['out_trade_no'] . "\r\n";
                                    $mailbody  .= "商品名称：" . $data['subject'] . "\r\n";
                                    $mailbody  .= "支付方式：支付宝支付\r\n";
                                    $mailbody  .= "交易金额：" . $data['total_amount'] . "\r\n";
                                    $mailbody  .= "支付时间：" . date('Y-m-d H:i:s', time()) . "\r\n";
                                    $mailtype  = 'TXT';
                                    require_once(DEDEINC . '/libraries/mail.class.php');
                                    $smtp        = new smtp($cfg_smtp_server, $cfg_smtp_port, true, $cfg_smtp_usermail, $cfg_smtp_password);
                                    $smtp->debug = 0;
                                    $smtp->sendmail($cfg_adminemail, $cfg_webname, $cfg_smtp_usermail, $mailtitle, $mailbody, $mailtype);
                                }
                                echo "success";
                                exit;
                            }
                            else
                            {
                                echo "fail";
                            }
                            /* 改变会员订单状态_支付成功 */
                        }
                        else if ($product == "member")
                        {
                            $row     = $dsql->GetOne("SELECT rank,exptime FROM #@__member_type WHERE aid='$pid' ");
                            $rank    = $row['rank'];
                            $exptime = $row['exptime'];
                            /*计算原来升级剩余的天数*/
                            $rs = $dsql->GetOne("SELECT uptime,exptime FROM #@__member WHERE mid='" . $mid . "'");
                            if ($rs['uptime'] != 0 && $rs['exptime'] != 0)
                            {
                                $nowtime = time();
                                $mhasDay = $rs['exptime'] - ceil(($nowtime - $rs['uptime']) / 3600 / 24) + 1;
                                $mhasDay = ($mhasDay > 0) ? $mhasDay : 0;
                            }
                            //获取会员默认级别的金币和积分数
                            $memrank = $dsql->GetOne("SELECT money,scores FROM #@__arcrank WHERE rank='$rank'");
                            //更新会员信息
                            $sql1 = " UPDATE #@__member SET rank='$rank',money=money+'{$memrank['money']}', scores=scores+'{$memrank['scores']}',exptime='$exptime'+'$mhasDay',uptime='" . time() . "' WHERE mid='" . $mid . "'";
                            //更新交易状态为已关闭
                            $sql2 = " UPDATE #@__member_operation SET sta='2',oldinfo='会员升级成功!' WHERE buyid='$buyid' ";
                            if ($dsql->ExecuteNoneQuery($sql1) && $dsql->ExecuteNoneQuery($sql2))
                            {
                                //作者：覃小华 2019年1月22日09:30:45 推广注册部分
                                //1、推荐人加佣金 2、付款人改成已购买用户  3、写收益记录（SVIP购买返现）
                                $tjrarr = $dsql->GetOne("SELECT tjrmid FROM #@__member WHERE mid = '" . $mid . "'");
                                file_put_contents("aarr_n_tjrarr.txt",print_r($tjrarr,true).PHP_EOL,FILE_APPEND);
                                if (!empty($tjrarr['tjrmid']))
                                {
                                    global $cfg_tgyjbl;
                                    $time    = time();
                                    $yongjin = $arr['money'] * $cfg_tgyjbl / 100;
                                    $yongjin = number_format($yongjin, 2);
                                    $tjrmid  = $tjrarr['tjrmid'];
                                    $sql     = "UPDATE #@__member set shouyi = (shouyi + $yongjin) WHERE mid = '$tjrmid'";
                                    file_put_contents("aarr_n_tjrarr1.txt",print_r($sql,true).PHP_EOL,FILE_APPEND);
                                    $dsql->ExecuteNoneQuery($sql);
                                    $sql = "UPDATE #@__member SET yigoumai = '1' WHERE mid = '" . $mid . "'";
                                    file_put_contents("aarr_n_tjrarr2.txt",print_r($sql,true).PHP_EOL,FILE_APPEND);
                                    $dsql->ExecuteNoneQuery($sql);
                                    $sql = "INSERT INTO #@__jj_shouyi (`tjrmid`,`mid`,`jine`,`chanpin`,`yongjin`,`time` ) VALUES ('$tjrmid','" . $mid . "','" . $arr['money'] . "','" . $arr['pname'] . "','$yongjin','$time')";
                                    file_put_contents("aarr_n_tjrarr3.txt",print_r($sql,true).PHP_EOL,FILE_APPEND);
                                    $dsql->ExecuteNoneQuery($sql);
                                }
                                //推荐end
                                if ($cfg_sendmail_bysmtp == 'Y' && !empty($cfg_smtp_server) && !empty($cfg_adminemail))
                                {
                                    $mailtitle = "【{$cfg_webname}】新订单通知";
                                    $mailbody  = '';
                                    $mailbody  .= "用户昵称：" . $username . "\r\n";
                                    $mailbody  .= "订单编号：" . $data['out_trade_no'] . "\r\n";
                                    $mailbody  .= "商品名称：" . $data['subject'] . "\r\n";
                                    $mailbody  .= "支付方式：支付宝支付\r\n";
                                    $mailbody  .= "交易金额：" . $data['total_amount'] . "\r\n";
                                    $mailbody  .= "支付时间：" . date('Y-m-d H:i:s', time()) . "\r\n";
                                    $mailtype  = 'TXT';
                                    require_once(DEDEINC . '/libraries/mail.class.php');
                                    $smtp        = new smtp($cfg_smtp_server, $cfg_smtp_port, true, $cfg_smtp_usermail, $cfg_smtp_password);
                                    $smtp->debug = 0;
                                    $smtp->sendmail($cfg_adminemail, $cfg_webname, $cfg_smtp_usermail, $mailtitle, $mailbody, $mailtype);
                                }
                                echo "success";
                                exit;
                            }
                        }
                    }
                }
                else
                {
                    echo "fail";
                }
            }
        }
        else
        {
            echo "fail";
        }
    } catch (Exception $e)
    {
        echo "fail";
    }
}